<template>
  <div>
    <el-container style="background: #f5f7f9;">
      <el-header style="background: #fff;padding: 12px 12px;height:auto;">
        <div>
          <el-form :model="queryData" :inline="true" size="small">
            <el-form-item>
              <el-input v-model="queryData.invoiceId" style="width: 320px;" placeholder="发票号" />
            </el-form-item>
            <el-form-item>
              <el-input v-model="queryData.refs" type="textarea" :rows="1" style="width: 300px;" placeholder="订单号" />
            </el-form-item>
            <el-form-item>
              <el-input v-model="queryData.batchAttr" type="textarea" :rows="1" style="width: 300px;" placeholder="柜号/提单号" />
            </el-form-item>
            <el-form-item v-if="!isOrgOwner">
              <el-select v-model="queryData.orgOwner" filterable clearable placeholder="请选择客户">
                <el-option v-for="item in customerOptions" :key="item.orgOwnerName" :value="item.orgOwner" :label="item.orgOwnerName" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-date-picker
                v-model="queryData.createAtRange"
                type="daterange"
                align="right"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="list">搜索</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-header>
      <el-main style="margin-top: 15px; background: #fff;padding: 12px 16px 0 16px;height: 100%;">
        <div style="height: 100%;display: flex;">
          <el-button v-if="!isOrgOwner" v-has="60401" type="primary" size="small" @click="add">生成账单</el-button>&nbsp;
          <el-button type="primary" size="small" @click="batchExport">导出账单</el-button>
        </div>
        <el-table :data="table_body" border stripe :max-height="tableHeight" @selection-change="selectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="invoiceId" label="发票号" />
          <el-table-column prop="orgOwner" label="客户" />
          <el-table-column prop="amount" label="金额" />
          <el-table-column prop="confirm" label="是否已确认">
            <template slot-scope="scope">
              <p v-if="scope.row.confirm">是</p>
              <p v-else>否</p>
            </template>
          </el-table-column>
          <el-table-column prop="at" label="创建时间" />
          <el-table-column prop="operation" label="操作">
            <template slot-scope="scope">
              <el-button v-has="60402" shape="circle" size="small" type="text" @click="detailList(scope.row)">查看明细</el-button>
              <div v-if="!isOrgOwner && !scope.row.confirm">
                <el-button v-has="60403" shape="circle" size="small" type="text" @click="append(scope.row)">增加明细</el-button>
                <el-button v-has="60404" shape="circle" size="small" type="text" @click="confirm(scope.row)">确认</el-button>
                <el-button v-has="60405" shape="circle" size="small" type="text" @click="del(scope.row)">删除</el-button>
              </div>
              <br>
              <a v-has="60406" :href="baseUrl+'/invoice/download?invoiceId=' + scope.row.id" download="账单.xlsx">导出</a>
            </template>
          </el-table-column>
        </el-table>
      </el-main>
      <el-footer style="padding:0;background: #fff;">
        <div style="text-align: right; padding-top: 10px;">
          <el-pagination background :current-page="queryData.currentPage" :page-sizes="[50,100]" :page-size="queryData.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="pageTotal" style="float:right;" @size-change="onPageSizeChange" @current-change="onPageChange" />
        </div>
      </el-footer>
    </el-container>
    <!--生成账单-->
    <el-dialog :visible.sync="openModal" top="0" width="60%" :mask-closable="false" :styles="styles">
      <el-row>
        <el-col :span="6" style="padding-right:10px">
          <el-input v-model="refNumber" type="textarea" placeholder="订单号" />
        </el-col>
        <el-col :span="6" style="padding-right:10px">
          <el-select v-model="txQueryData.orgOwner" filterable clearable placeholder="请选择客户">
            <el-option v-for="item in customerOptions" :key="item.orgOwnerName" :value="item.orgOwner" :label="item.orgOwnerName" />
          </el-select>
        </el-col>
        <el-col :span="12" style="padding-right:10px">
          <el-date-picker
            v-model="txQueryData.start"
            type="date"
            placeholder="开始日期"
            format="yyyy-MM-dd"
          />
          <el-date-picker
            v-model="txQueryData.end"
            type="date"
            placeholder="结束日期"
            format="yyyy-MM-dd"
          />
        &nbsp;
          <el-button type="primary" @click="txList">搜索</el-button>
        </el-col>
      </el-row>

      <el-table :data="tx_data" stripe style="width: 100%" @selection-change="detailSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="orderNumber" label="订单号" />
        <el-table-column prop="orgOwner" label="客户" />
        <el-table-column prop="amount" label="金额" />
        <el-table-column prop="currency" label="币种" />
        <el-table-column prop="chargeType" label="费用类型" />
        <el-table-column prop="txDate" label="交易时间" />
      </el-table>
      <el-pagination background :current-page="queryData.currentPage" :page-sizes="[50,100]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="txPageTotal" style="float:right;" @size-change="onTxPageSizeChange" @current-change="onTxPageChange" />

      <div slot="footer" class="dialog-footer">
        <el-button style="margin-right: 8px" @click="openModal = false">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
    </el-dialog>
    <!--账单明细-->
    <el-dialog :visible.sync="openDetailModal" top="0" width="60%" :mask-closable="false" :styles="styles">
      <el-row>
        <el-col :span="6" style="padding-right:10px">
          <el-input v-model="refNumber" type="textarea" placeholder="订单号" />
        </el-col>
        <el-col :span="6" style="padding-right:10px">
          <el-button type="primary" size="small" @click="detailList">搜索</el-button>
        &nbsp;
          <el-button v-if="!isOrgOwner" type="primary" size="small" @click="detaiDel">批量删除</el-button>
        </el-col>
      </el-row>
      <el-table :data="detail_data" stripe style="width: 100%" @selection-change="detailSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="orderNumber" label="订单号" />
        <el-table-column prop="orgOwner" label="客户" />
        <el-table-column prop="channelName" label="渠道" />
        <el-table-column prop="amount" label="金额" />
        <el-table-column prop="currency" label="币种" />
        <el-table-column prop="chargeType" label="费用类型" />
        <el-table-column prop="txDate" label="交易时间" />
      </el-table>
      <el-pagination
        background
        :current-page="detailQueryData.currentPage"
        :page-sizes="[50,100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="txPageTotal"
        style="float:right;"
        @size-change="onDetailPageSizeChange"
        @current-change="onDetailPageChange"
      />
      <div slot="footer" class="dialog-footer">
        <el-button style="margin-right: 8px" @click="openDetailModal = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import dateFormat from 'dateformat'
import request from '@/utils/request'
import { mapState } from 'vuex'
import config from '@/settings'
import { copyProperty } from '@/utils/tools'
const BASE_URL = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro
export default {
  data() {
    return {
      baseUrl: BASE_URL,
      openModal: false,
      openDetailModal: false,
      tx_data: [

      ],
      table_body: [

      ],
      detail_data: [

      ],
      styles: {
        height: 'calc(100% - 55px)',
        overflow: 'auto',
        paddingBottom: '53px',
        position: 'static'
      },
      queryData: {
        invoiceId: '',
        orgOwner: '',
        pageSize: 50,
        currentPage: 0,
        refs: '',
        batchAttr: '',
        createAtRange: []
      },
      txQueryDataDefault: {
        orderNumbers: [],
        start: '',
        end: '',
        create: false,
        warehouseId: '',
        orgOwner: '',
        pageSize: 50,
        currentPage: 0
      },
      txQueryData: {
        orderNumbers: [],
        start: '',
        end: '',
        create: false,
        warehouseId: '',
        orgOwner: '',
        pageSize: 50,
        currentPage: 0
      },
      detailQueryData: {
        orderId: [],
        id: '',
        pageSize: 50,
        currentPage: 0
      },
      refNumber: '',
      pageTotal: 0,
      pageSizeOpts: [50, 100],
      txPageTotal: 0,
      detailSelectedIds: [],
      invoiceIds: []
    }
  },
  computed: {
    tableHeight() {
      return document.documentElement.clientHeight - 330
    },
    pageSize() {
      return this.pageSizeOpts[0]
    },
    ...mapState(//
      {
        customerOptions: state => state.base.customerOptions,
        profile: state => state.user
      }
    ),
    isOrgOwner() {
        return this.profile.orgOwner
    }
  },
  created() {
    this.list()
    this.$store.dispatch('getCustomerOptions')
  },
  mounted() {
  },
  methods: {
    selectionChange(val) {
      const ids = []
      val.forEach(e => {
        ids.push(e.id)
      })
      this.invoiceIds = ids
    },
    batchExport() {
      if (this.invoiceIds.length === 0) {
        this.$message({
          showClose: true,
          message: '请先选择',
          type: 'error',
          duration: 0
        })
        return
      }
      window.open(this.baseUrl + '/invoice/downloads?invoiceIds=' + this.invoiceIds.join(','))
    },
    txList() {
      if (this.txQueryData.start) {
        this.txQueryData.start = dateFormat(this.txQueryData.start, 'yyyy-mm-dd')
      }
      if (this.txQueryData.end) {
        this.txQueryData.end = dateFormat(this.txQueryData.end, 'yyyy-mm-dd')
      }
      if (this.refNumber) {
        this.txQueryData.orderNumbers = this.refNumber.split(/\n|,|，/)
      } else {
        this.txQueryData.orderNumbers = []
      }
      request({
        url: 'invoice/transaction',
        method: 'post',
        data: this.txQueryData
      }).then(res => {
        if (res.success) {
          if (this.txQueryData.create !== 'false' && this.txQueryData.create) {
            this.list()
            this.txQueryData.create = false
          }
          if (!res.data) {
            // this.openModal = false
            this.tx_data = []
            this.txPageTotal = 0
          } else {
            this.tx_data = res.data.page.records
            this.txPageTotal = res.data.page.total
          }
        }
      })
    },
    detailList(row) {
      this.openDetailModal = true
      if (row && row.id) {
        this.detailQueryData.id = row.id
        this.detailQueryData.orderNumbers = []
      } else if (this.refNumber) {
        this.detailQueryData.orderNumbers = this.refNumber.split(/\n|,|，/)
      } else {
        this.detailQueryData.orderNumbers = []
      }
      request({
        url: 'invoice/detail',
        method: 'post',
        data: this.detailQueryData
      }).then(res => {
        if (res.success) {
          if (res.data) {
            this.detail_data = res.data.records
            this.txPageTotal = res.data.total
          }
        }
      })
    },
    detailSelectionChange(sel) {
      if (sel.length > 0) {
        const ids = []
        sel.forEach(ele => {
          ids.push(ele.txId)
          this.detailSelectedIds = ids
        })
      } else {
        this.detailSelectedIds = []
      }
    },
    detaiDel() {
      if (this.detailSelectedIds.length === 0) {
        this.$message({
          showClose: true,
          message: '请先选择',
          type: 'error',
          duration: 0
        })
        return
      }
      request({
        url: 'invoice/del/txs',
        method: 'post',
        data: { id: this.detailQueryData.id, txIds: this.detailSelectedIds }
      }).then(res => {
        if (res.success) {
          this.detailList()
        }
      })
    },
    list() {
      request({
        url: 'invoice/query',
        method: 'post',
        data: this.queryData
      }).then(res => {
        if (res.success) {
          if (res.data) {
            this.table_body = res.data.records
            this.pageTotal = res.data.total
          }
        }
      })
    },
    submit() {
      if (this.txQueryData.id) {
        // 账单里面追加流水
        if (this.detailSelectedIds.length === 0) {
          this.$message({
            showClose: true,
            message: '请先选择',
            type: 'error',
            duration: 0
          })
          return
        }
        this.appendSubmit()
        return
      }
      this.txQueryData.create = true

      let hasOption = false
      if (this.txQueryData.start) {
        hasOption = true
      }
      if (this.txQueryData.end) {
        hasOption = true
      }
      if (this.refNumber) {
        hasOption = true
      }

      if (this.txQueryData.orgOwner) {
        hasOption = true
      }
      if (!hasOption) {
        this.$confirm('你没有筛选条件,是否所有客户都出账单?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.txList()
        })
      } else {
        this.txList()
      }
    },
    add() {
      copyProperty(this.txQueryData, this.txQueryDataDefault)
      this.txList()
      this.openModal = true
    },
    append(row) {
      this.txQueryData.id = row.id
      this.txQueryData.orgOwner = row.orgOwnerId
      this.add()
    },
    appendSubmit() {
      request({
        url: 'invoice/add/txs',
        method: 'post',
        data: { id: this.txQueryData.id, txIds: this.detailSelectedIds }
      }).then(res => {
        if (res.success) {
          this.openModal = false
          this.list()
          this.$message.success('成功')
        }
      })
    },
    confirm(row) {
      this.$confirm('确认账单后,不能再编辑账单?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        request({
        url: 'invoice/confirm?id=' + row.id,
        method: 'get'
      }).then(res => {
          if (res.success) {
            this.$message({
              message: '操作成功',
              type: 'success'
            })
            this.list()
          }
        })
      })
    },
    del(row) {
      request({
        url: 'invoice/del?id=' + row.id,
        method: 'delete'
      }).then(res => {
        if (res.success) {
          this.$message({
            message: '操作成功',
            type: 'success'
          })
          this.list()
        }
      })
    },
    onPageSizeChange(pageSize) {
      this.queryData.pageSize = pageSize
      this.list()
    },
    onPageChange(page) {
      this.queryData.currentPage = page
      this.list()
    },
    onTxPageSizeChange(pageSize) {
      this.txQueryData.pageSize = pageSize
      this.txList()
    },
    onTxPageChange(page) {
      this.txQueryData.currentPage = page
      this.txList()
    },
    onDetailPageSizeChange(pageSize) {
      this.detailQueryData.pageSize = pageSize
      this.detailList()
    },
    onDetailPageChange(page) {
      this.detailQueryData.currentPage = page
      this.detailList()
    }
  }
}
</script>
<style>
    .demo-drawer-footer{
        width: 100%;
        position: absolute;
        bottom: 0;
        left: 0;
        border-top: 1px solid #e8e8e8;
        padding: 10px 16px;
        text-align: right;
        background: #fff;
    }

    .demo-upload-list{
        display: inline-block;
        width: 60px;
        height: 60px;
        text-align: center;
        line-height: 60px;
        border: 1px solid transparent;
        border-radius: 4px;
        overflow: hidden;
        background: #fff;
        position: relative;
        box-shadow: 0 1px 1px rgba(0,0,0,.2);
        margin-right: 4px;
    }
    .demo-upload-list img{
        width: 100%;
        height: 100%;
    }
    .demo-upload-list-cover{
        display: none;
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        background: rgba(0,0,0,.6);
    }
    .demo-upload-list:hover .demo-upload-list-cover{
        display: block;
    }
    .demo-upload-list-cover i{
        color: #fff;
        font-size: 20px;
        cursor: pointer;
        margin: 0 2px;
    }
</style>
